using UnityEngine;
using System.Collections;


[ExecuteInEditMode]	
public class Background : MonoBehaviour {

	public Material newMaterial;
	public float targetAlpha = 1.0f;
	public float gridSize = 15.0f;
	public int xLength = 2;
	public int yLength = 2;

	Mesh mesh;
	Color[] colors;
	
	// Use this for initialization
	void Start () {
		gameObject.transform.position = new Vector3(-7.964561f, -1.376864f, 3.0f);
		gameObject.transform.localScale = new Vector3(1.066013f, 0.5735569f, 0.5735569f);
		gameObject.name = "background";
		
		gameObject.AddComponent("MeshFilter");
		gameObject.AddComponent("MeshRenderer");
		mesh = GetComponent<MeshFilter>().mesh;
	
		mesh.Clear();
		
		// vertices ---------------------------------------------------------------------------------
		ArrayList verts = new ArrayList();
	
		for (int y = 0; y < yLength; ++y)
		{
			for (int x = 0; x < xLength; ++x)
			{
				verts.Add( new Vector3( (x*gridSize), (y*gridSize), transform.position.z) );
			}
		}

		mesh.vertices = (Vector3[]) verts.ToArray( typeof( Vector3 ) );
	
		// uv's ----------------------------------------------------------------------------------------
		Vector2[] uvs = new Vector2[verts.Count];
	
		for (int i=0;i<uvs.Length;i++) {
			Vector3 v = (Vector3)verts[i];
			uvs[i].x = v.x;
			uvs[i].y = v.y;
		}
		mesh.uv = uvs;
	
		// triangles ---------------------------------------------------------------------------------
		ArrayList tris = new ArrayList();
	
		for (int y = 0; y < yLength-1; ++y)
		{
			for (int x = 0; x < xLength-1; ++x)
			{
				int vertHere = x+(y*xLength);
				int vertAbove = x+((y+1)*xLength);
				tris.Add(vertHere); 
				tris.Add(vertAbove);
				tris.Add(vertAbove+1);
	
				tris.Add(vertHere);
				tris.Add(vertAbove+1);
				tris.Add(vertHere+1);
				//glog.debug(x + "," + y + ": " +
				//	vertHere + "," + vertAbove + "," + (vertAbove+1) + " " +
				//	vertHere + "," + (vertAbove+1) + "," + (vertHere+1));
			}
		}
		
		mesh.triangles = (int[]) tris.ToArray( typeof(int));
		mesh.RecalculateNormals();
		mesh.RecalculateBounds();
	
		// vertex colors ------------------------------------------------------------------------------
		glog.debug ("mesh.vertices.Length " + mesh.vertices.Length);
		colors = new Color[mesh.vertices.Length];
	
		for (int i=0;i<mesh.vertices.Length;i++)
		{
			colors[i].r = 1;
			colors[i].g = 1;
			colors[i].b = 1;
			colors[i].a = targetAlpha;
		}
		mesh.colors = colors;
	
		renderer.castShadows = false;
		renderer.receiveShadows = false;
		renderer.material = newMaterial;
	}

}
